package com.yanxml.core.java.reference.soft_reference;

import org.junit.Assert;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;

public class SoftReferenceTest_GC {

    public static class MyBigDataObject {
        int[] data = new int[128];
    }

    public static void softReference_un_gc_afterOutOfMemory() {
        // init data
        SoftReference<List<String>> testNumberRef = new SoftReference<List<String>>(new ArrayList<>(100));

        // do case
        // max max size object

        System.gc();
        List<MyBigDataObject> bigDataObjectList = new ArrayList<>();

        try {
            for (int i = 0; i < 100; i++) {
                MyBigDataObject obj = new MyBigDataObject();
                bigDataObjectList.add(obj);
            }
        } catch (OutOfMemoryError outOfMemoryError) {
            // do nothing
            System.out.println(outOfMemoryError);
        }


        // assert
        System.out.println("soft reference is null?" + (null == testNumberRef));
        System.out.println("soft reference object is null?" + (null == testNumberRef.get()));
    }

    public static void softReference_gc_afterOutOfMemory() {
        // init data
        SoftReference<List<String>> testNumberRef = new SoftReference<List<String>>(new ArrayList<>(100));

        // do case
        // max max size object

        System.gc();
        List<MyBigDataObject> bigDataObjectList = new ArrayList<>();

        try {
            for (int i = 0; i < 8000; i++) {
                MyBigDataObject obj = new MyBigDataObject();
                bigDataObjectList.add(obj);
            }
        } catch (OutOfMemoryError outOfMemoryError) {
            // do nothing
            System.out.println(outOfMemoryError);
        }


        // assert
        System.out.println("soft reference is null?" + (null == testNumberRef));
        System.out.println("soft reference object is null?" + (null == testNumberRef.get()));
    }

    /**
     * VM Options
     * -Xms4m -Xmx4m -Xmn2m
     */
    public static void main(String[] args) {

        // test case 1 . un_gc
//        softReference_un_gc_afterOutOfMemory();

        // test case2 . gc
        softReference_gc_afterOutOfMemory();

    }
}
